<!--公告编辑-->
<template>
<div class="app-container">
	<div class="edit">
		<el-form :model="formLabel" label-width="150px" :inline="true" :rules="rules" ref="formLabel">
			<el-form-item label="公告标题：" class="is-required offsetR" prop="title">
            	<el-input maxlength='20' v-model="formLabel.title" placeholder="请输入公告标题" size="mini"  class="wd300"></el-input>
            	<span class="len">{{length}}/20</span>
          	</el-form-item>
          	<el-form-item label="发布到以下机构：" class="offsetR toBlock is-required" prop="treeSelect">
            <ztree-select class="wd300" v-model="formLabel.treeSelect" v-on:namearr="namearr" multiple :treedata="organizationUnitTree" :childprops="childprops" @change='getTreeSelect'></ztree-select>
          	 <!--  <div class="wd720"> -->
	          	<!--<span class="setColor" @click="openTree = true" v-for="org in formLabel.orgs" v-if="formLabel.orgs">{{org.fullName}}</span>-->
	          	<!-- <span class="totalCount" @click="openTree = true" v-if="treename">已选中&nbsp;{{formLabel.orgsLen}}&nbsp;个组织</span> -->
	          <!-- </div> -->
	         <!--  <el-button size="mini" @click="openTree = true" class="toBlock"><i class="iconfont icon-organization"></i>&nbsp;{{formLabel.org}}</el-button>
	          <div class="hiddenInput"> -->
	          	<!--<el-input type="hidden"  v-model="formLabel.orgs"></el-input>-->
	         <!--  </div> -->
	          <!-- <el-dialog title="选择组织" @close="backs" :visible.sync="openTree" :close-on-click-modal='false' width='500px'>
	            <div class="fix">
	              <el-tree
	                :data="organizationUnitTree"
	                show-checkbox
	                node-key="id"
	                :default-expand-all='true'
	                :default-checked-keys="treeArr"
	                :props="defaultProps"
	                ref="tree"
	                :check-strictly="true"
	               >
	              </el-tree>
	            </div>
	            <div slot="footer" class="dialog-footer">
	              <el-button @click="backs">取 消</el-button>
	              <el-button type="primary"  @click="getCheckedKeys()">确 定</el-button>
	            </div>
	          </el-dialog> -->
	        </el-form-item>	
	        <el-form-item label="公告内容：" class="offsetR toBlock is-required" prop='content'>
	          <!--<el-input
	            type="textarea"
	            :autosize="{minRows:6}"
	            placeholder="请输入内容"
	            v-model="formLabel.content" style="width:730px">
	          </el-input>-->
	          <editor class='iframe'
	          	style="width: 730px !important;font-size: 13px !important;"
					v-model='formLabel.content'
					@show='editors'
					>
			  </editor>
	        </el-form-item>
	        <el-row class="center">	          
	          <el-button type="info" size="small" @click="goBack()" >取消</el-button>
	          <el-button type="primary" size="small" @click="submitForm('formLabel')" :loading="loading">保存</el-button>
	        </el-row>
		</el-form>
	</div>
</div>
</template>

<script>
	import editor from '@/components/editor';
  import ztreeSelect from "@/components/z-select/index.vue";
export default {
	components:{
			editor,
      ztreeSelect
		},
  data() {
    return {
      loading:false,
      //数组子级相关参数
      childprops: {
        name: "displayName", //显示名字
        children: "orgs", //子级字段名
        lv: "depth" //当前层级
      },
      namearr:[],
    	id:'0',
    	length:0,
    	title:'',
    	formLabel: {
    		title:'',
    		org:'关联组织',
    		orgs:[],
    		orgsLen:0,
    		content:'',
        treeSelect:[],
    	},
    	defaultProps: {
	      children: 'organizationUnits',
	      label: 'displayName'
	    },
	    organizationUnitTree: [],
	    treeArr:[],//选中的树
	    treeArrLen:0,
	    treename:[],
     	openTree: false,
     	rules: {
	        title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
	        treeSelect: [{ required: true, message: '请至少选择一个组织', trigger: 'change' }],
	        content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
	      },
	      from: false // 来自哪里，false为新建，true为更新
    }
  },
  mounted() {
  	console.log('------------')
    this.id = this.$route.params.id
    console.log(this.id)
    if (this.id != '0' && this.id != null) {
      this.getInfo();
      this.from = true
    }
    this.getTree()
  },
  watch:{
  	formLabel:{
  		handler(val,old){
	  		this.length = this.formLabel.title.length;
	  		console.log(this.length);
  		},
  		deep:true
  	}
  },
  methods: {
  		//得到权限集合
	treearray(data) {
		console.log(data)
		var treeArr = [];
		var treeNames = [];
		data.map(function (item) {
			
			if (item.isCheck) {
				treeArr.push(item.id)
				treeNames.push(item.fullName)
			}
			console.log(item.organizationUnits.length)
			if (item.organizationUnits&&item.organizationUnits.length > 0) { //遍历2级
				
				item.organizationUnits.map(function (elem) {
					if (elem.isCheck) {
						console.log(item.id + 'yiyiyi')
						treeArr.push(elem.id)
						treeNames.push(elem.fullName)
					}
					if (elem.organizationUnits&&elem.organizationUnits.length > 0) { //遍历3级
						elem.organizationUnits.map(function (obj) {
							if (obj.isCheck) {
								treeArr.push(obj.id)
								treeNames.push(obj.fullName)
							}

							if (obj.organizationUnits&&obj.organizationUnits.length > 0) { //遍历4级
								obj.organizationUnits.map(function (last) {
									if (last.isCheck) {
										treeArr.push(last.id)
										treeNames.push(last.fullName)
									}
									//遍历3级
								})
							}
						})
					}
				})
			}
		})
		this.formLabel.orgsLen = treeArr.length;
    this.treeSelect=treeArr;
    console.log(this.treeSelect);
    console.log('-------------------------------------11111111111111');
		return {treeArr,treeNames};
	},
  	// 信息
  	getInfo(){
		const that = this
	    const params = {
	        id: this.id
	    }
	    this.post(params, 'services/app/notice/GetNoticeDetail').then(rs => {
	        // console.log('-------------')
	        // console.log(rs)
	        if(rs.result.organizationUnitIds){
	            this.formLabel.treeSelect = rs.result.organizationUnitIds;
	            console.log('8989')
	            console.log(this.formLabel.treeSelect)
	        }
	        if (rs.success) {
				    that.from = true
      			that.formLabel.title = rs.result.title
      			that.formLabel.content = rs.result.content
      			// that.organizationUnitTree = rs.result.organizationUnitTree
      			// that.treearray(rs.result.organizationUnitTree)
      			that.treeArr = rs.result.organizationUnitTree
            that.formLabel.treeSelect = that.treeArr;
      			//that.treename = that.treearray(that.organizationUnitTree).treeNames
	        }
	    })
  	},
  	// 树
    getTree() {
      let params={
          "queryType": 0
      }
      this.post(params, 'services/app/common/GetCurrentOrganizationUnitsByType').then(rs => {
        // console.log('-----------')
        // console.log(rs)
        if (rs.success) {
          let arr = [];
          arr.push(rs.result);
          this.organizationUnitTree = arr;
          // console.log(this.organizationUnitTree)
        }
      })
    },
    // 验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
      	console.log('vvvv')
      	console.log(this.$refs[formName].validate)
        if (valid) {
          this.loading = true;
          // alert('submit')
          this.save()
        } else {
          console.log('error submit')
          return false
        }
      })
    },
    // 树值
    // getCheckedNodes() {
    //   console.log(this.$refs.tree.getCheckedNodes())
    //   this.formLabel.orgs = this.$refs.tree.getCheckedNodes();
    //   this.formLabel.orgsLen = this.formLabel.orgs.length;
    // },
    // backs(){
    // 	this.openTree = false
    // 	this.$refs.tree.setCheckedKeys(this.treeSelect);
    // },
    // getCheckedKeys() {
    //   this.openTree = false
    //   // console.log(this.$refs.tree.getCheckedKeys())
    //   this.getCheckedNodes()
    //   this.treeSelect = this.$refs.tree.getCheckedKeys()
    //   this.id = this.$route.params.id
    // 	console.log(this.id)
    // },
    getTreeSelect(val){
      console.log(val)
      // console.log('------------------');
      this.formLabel.treeSelect = val;
    },
    // 保存
    save() {
      const that = this
      if (that.id=='0') {
        console.log('走创建')
        // 创建接口的参数
        const add = {
          title : this.formLabel.title,
          content: this.formLabel.content
        }
        const paramsadd = {
          organizationUnitIds : this.formLabel.treeSelect, // 组织树
          notice : add
         // ,id:this.id
        }
        console.warn(paramsadd)
        // 判断走创建是不是选了组织权限
        if (paramsadd.organizationUnitIds) {
          that.post(paramsadd, 'services/app/notice/CreateNotice').then(rs => {
            console.log(rs)
            if (rs.success) {
              this.loading = false;
              console.log('成功-----------')
              // this.$router.push({
              //   name: 'announce'
              // });
              this.$router.go(-1)
			        this.succeeNot();
            }else{
              this.failNot(rs.error.message);
              this.loading = false;
            }
          })
        } else {
          console.log('error----------')
        }
      } else {
        console.log('走编辑')
        // 编辑接口的参数
        const update = {
          id:this.id,
          title : this.formLabel.title,
          content: this.formLabel.content
        }
        const paramsupdate = {
          organizationUnitIds : this.formLabel.treeSelect, // 组织树
          notice : update
        }
        console.log('8989898')
        console.log(paramsupdate)
        //console.warn(paramsupdate)
        // 判断是不是选了组织权限
        if (paramsupdate.organizationUnitIds) {
        	console.log('999999')
          	that.post(paramsupdate, 'services/app/notice/UpdateNotice').then(rs => {
            // if(as.success){
            //   this.stateSvc.go('home.announce')
            //   console.log('编辑成功')
            // }else{
            //   console.log('编辑失败')
            // }
            // this.stateSvc.go('home.announce')
            console.log(rs)
            if (rs.success) {
              this.loading = false;
              console.log('成功------------')
              // this.$router.push({
              //   name: 'announce'
              // });
              this.$router.go(-1)
              this.succeeNot();              
            }else{
              this.loading = false;
            	this.failNot(rs.error.message);
            }
          })
        }else {
          	
        }
      }
    },
    goBack(){
    	this.$router.push({
    		name:'announce'
    	})
    },
    //保存成功提示
    succeeNot(){
    	var txt = '';
    	if (this.id=='0') {
    		txt='公告新建成功'
    	} else{
    		txt='公告保存成功'
    	}
    	const h = this.$createElement;
      	this.$notify({
          title: '成功',
          message: txt,
          type: 'success',
          customClass:"el-notification-success"
        });
    },
    //保存失败提示
    failNot(message){
    	const h = this.$createElement;
      	this.$notify.error({
          title: '保存失败',
          message: message,
          duration: 0,
          customClass:"el-notification-error"
        });
    },
    
//  fuwenben
	editors(val){
		this.formLabel.content = val;
	}
  }
}
</script>

<style lang="scss" scoped>
.fix{
    height: 400px;
    overflow-y: auto;
    margin-left:100px;
}
.len{
	color:#d7d7d7;
	position: relative;
	top:5px;
}
.wd720{
	width:720px;
}
.wd300{
  width:300px;
}
.edit{
	padding:20px;
	padding-top: 50px;
}
.offsetR{
    margin-left:93px;
  }
  .center{
    text-align: center;
  }
  .toBlock{
    display:block;
  }
  .el-form-item.is-required .el-form-item__label:before{
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .setColor{
    color: #333;
    border-radius: 5px;
    background-color: #efefef;
    padding: 5px;
    border: 1px solid #d7d7d7;
    margin:0 20px 10px 0;
    display: inline-block;
    line-height:10px;
  }
  .hiddenInput{
    width:400px;
    height:0;
  }
  .wd230{
    width: 230px;
  }
  .totalCount{color: #0c7bde;}
  .iframe{height: 260px !important;}
</style>
